<?php


namespace app\library\traits;


use app\core\exception\ApiException;
use think\Model;

trait CommonModel
{
//    use SoftDelete;  //软删除

    //可以显示的字段
    protected $canShowFields = [];

    public function list()
    {
        $page = input('page', 1);
        $count = input('count', 10);
        $from = ($page - 1) * $count;
        $data['list'] = $this->limit($from, $count)
            ->column(implode(',', $this->canShowFields));
        $data['total'] = $this->count($this->canShowFields[0]);
        $data['page'] = $page;
        $data['count'] = $count;
        $data['from'] = $from;
        return $data;
    }

    /**
     *
     * 获得该类的数据  这个是基类不能动，子类去继承该方法，就可以重写
     * @param $id
     * @return array|Model|null
     * @throws ApiException
     */
    public function getOne($id)
    {
        $model = self::find((int)$id);
        $model || error('该' . $this->noticeName . '信息不存在');
        return $model;
    }


    /**
     * 保存数据  这个是基类不能动，子类去继承该方法，就可以重写
     * @return bool
     * @throws ApiException
     */
    public function saveRow()
    {
        validate(request()->post(), $this->insertRule, $this->message);
        return $this->save(request()->post());
    }

    /**
     * 更新一条数据  这个是基类不能动，子类去继承该方法，就可以重写
     * @param $id
     * @return bool
     * @throws ApiException
     */
    public function updateRow($id)
    {
        $model = $this->getOne($id);
        $data = changeRowData($this->updateFields, request()->post(), $model->toArray());
        count($data) || error('没有字段发生改变，请提交要改变的数据');
        validate($data, $this->updateRule, $this->message);
        return $model->save($data);
    }

    /**
     * 删除一条数据
     * @param $id
     * @return bool
     * @throws ApiException
     */
    public function deleteOne($id)
    {
        $model = $this->getOne($id);
        return $model->delete();
    }
}